#!coding:utf-8
"""
Routines for configuring 
"""
import logging.handlers
import sys,os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cvirt.settings")

from cvirt.common.loghandler import ZipRotatingFileHandler as zip_log
from ConfigParser import ConfigParser
from cvirt.manager.models import Setting

DEFAULT_LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s"
DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

"配置入口有两个：testcase和tasks"
def setup_logging(conf=None):
    """
    Sets up the logging options for a log with supplied name

    :param conf: Mapping of untyped key/values from config file
    """
    if not conf: conf = load_settings()

    # If either the CLI option or the conf value
    # is True, we set to True
    debug = conf.get_bool('cvirt.debug')

    root_logger = logging.root
    if debug:
        root_logger.setLevel(logging.DEBUG)
    else:
        root_logger.setLevel(logging.INFO)


    formatter = logging.Formatter(DEFAULT_LOG_FORMAT, DEFAULT_LOG_DATE_FORMAT)

    logpath = conf.get('cvirt.log.path')
    if logpath and not os.path.exists(logpath):
        os.makedirs(conf.get('cvirt.log.path'))
        
    #logfile = None

    use_syslog = conf.get_bool('cvirt.use_syslog')

    if use_syslog:
        handler = logging.handlers.SysLogHandler(address='/dev/log')
    elif logpath:
        logfile = os.path.join(logpath,"cvirt.log")
        if conf.get_bool('cvirt.log.compress',True):
            handler = zip_log(logfile,compress_mode='gz')
        else:
            handler = logging.handlers.WatchedFileHandler(logfile)
    else:
        handler = logging.StreamHandler(sys.stdout)

    handler.setFormatter(formatter)
    root_logger.addHandler(handler)



def _load_file_conf(filename):
    c = ConfigParser()
    try:
        c.read(filename)
        allconf = {}
        for section in c.sections():
            allconf.update(dict(c.items(section)))
        return allconf

    except Exception as e:
        print 'can not read config of cvirt: cvirt.conf',e
        sys.exit(-1)

def load_settings(filepath='/opt/tcloud/cvirt.conf',for_test=False):

    global configcache
    if configcache:
        return configcache
    cvirtpath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    if not os.path.exists(filepath):
        filepath = os.path.join(cvirtpath, "conf","cvirt.conf")

        #测试用
    if for_test:
        filepath = os.path.join(cvirtpath, "conf","test.conf")

    configs = Setting.objects.all()
    configmap = Config(dict([(c.name,c.value) for c in configs]))
    #update service host conf
    configmap.update(_load_file_conf(filepath))

    configcache = configmap
    return configmap

configcache = {}#config cache


class Config(object):
    """模拟dict，增加类型转换的方法"""
    def __init__(self,conf):
        self.conf = conf
    
    def __getitem__(self, name):
        if self.conf.has_key(name): return self.conf[name]
    
    def get(self,name,default=None):
        return self[name] if self[name] else default
    
    def update(self,otherdict):
        self.conf.update(otherdict)
        
    def items(self):
        return self.conf.items()
    
    def get_bool(self,name,default=False):
        return self._get_option(name,type='bool',default=default)
        
    def get_int(self,name,default=None):
        return self._get_option(name,type='int',default=default)
    
    def get_float(self,name,default=None):
        return self._get_option(name,type='float',default=default)
        
    def _get_option(self, option, **kwargs):
        if option in self.conf:
            value = self.conf[option]
            type_ = kwargs.get('type', 'str')
            if type_ == 'bool':
                if hasattr(value, 'lower'):
                    return value.lower() == 'true'
                else:
                    return value
            elif type_ == 'int':
                return int(value)
            elif type_ == 'float':
                return float(value)
            else:
                return value
        elif 'default' in kwargs:
            return kwargs['default']
        else:
            raise KeyError("option '%s' not found" % option)
        
if __name__ == '__main__':
    conf = load_settings()
    print conf.get_int('dasd',868)
    print conf.get('ha.password',None)